
function y = difD3(w,P,X,Z,R,C)

y = 0;
PZZ = calculatePHat(w,X,Z,R,C);

   
    for ii=1:R
        for jj=1:C
            if jj~= C
                y = y + myfunc(ii,jj,P,PZZ);
            else
                y =y + myfunc(ii,jj,P,PZZ)*C;
            end
        end
    end
    

end



function v = myfunc(ii,jj,P,PZ)

p = P(ii,jj);
pHat = PZ(ii,jj);

v = (ii - jj)* sign(p - pHat)*(p - pHat)^2;

% if pHat ~=0
%     v = (ii - jj)* sign(p(ii, jj) - pHat(ii, jj))*(p(ii, jj) - pHat(ii, jj))^2;
% else
%     v = 0;
% end

end

